package com.promise.jokerdream.viewmodel

import android.app.Application
import android.util.Log
import android.webkit.WebView
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.database.account.UserAccount
import com.promise.jokerdream.network.HttpApiConstants
import com.promise.jokerdream.database.entity.KnightDreamGameConfigEntity
import com.promise.jokerdream.work.manager.KnightDreamWorkManager
import com.promise.jokerdream.work.knight.dream.KnightDreamWork
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

import com.promise.jokerdream.utils.IncognitoPreferenceManager

/**
 * 主应用ViewModel，管理应用状态和业务逻辑
 */
class MainViewModel(application: Application) : AndroidViewModel(application) {
    
    // WebView相关状态
    private val _currentUrl = MutableStateFlow(HttpApiConstants.PhoneUrls.home)
    val currentUrl: StateFlow<String> = _currentUrl.asStateFlow()
    
    private val _webViewProgress = MutableStateFlow(0)
    val webViewProgress: StateFlow<Int> = _webViewProgress.asStateFlow()

    // 无痕模式状态
    private val _isIncognitoEnabled = MutableStateFlow(false)
    val isIncognitoEnabled: StateFlow<Boolean> = _isIncognitoEnabled.asStateFlow()
    
    private val _canGoBack = MutableStateFlow(false)
    val canGoBack: StateFlow<Boolean> = _canGoBack.asStateFlow()
    
    private val _canGoForward = MutableStateFlow(false)
    val canGoForward: StateFlow<Boolean> = _canGoForward.asStateFlow()
    
    // 用户账号相关状态
    private val _currentAccount = MutableStateFlow<UserAccount?>(null)
    val currentAccount: StateFlow<UserAccount?> = _currentAccount.asStateFlow()
    
    // 抽屉状态
    private val _isDrawerOpen = MutableStateFlow(false)
    val isDrawerOpen: StateFlow<Boolean> = _isDrawerOpen.asStateFlow()
    
    // WebView实例引用
    private var webViewInstance: WebView? = null
    
    // WebView状态
    private val _webViewReady = MutableStateFlow(false)
    val webViewReady: StateFlow<Boolean> = _webViewReady.asStateFlow()
    
    // 战斗过程解析进度
    private val _fightProcessProgress = MutableStateFlow<Pair<Int, Int>?>(null)
    val fightProcessProgress: StateFlow<Pair<Int, Int>?> = _fightProcessProgress.asStateFlow()
    
    init {
        loadCurrentAccount()
        loadIncognitoState()
    }
    
    /**
     * 加载无痕模式状态
     */
    private fun loadIncognitoState() {
        _isIncognitoEnabled.value = IncognitoPreferenceManager.isIncognitoEnabled(getApplication())
    }

    /**
     * 切换无痕模式
     */
    fun toggleIncognitoMode() {
        val newState = !_isIncognitoEnabled.value
        _isIncognitoEnabled.value = newState
        IncognitoPreferenceManager.setIncognitoEnabled(getApplication(), newState)
        // 刷新WebView以应用更改
        webViewInstance?.reload()
    }

    /**
     * 设置WebView实例
     */
    fun setWebView(webView: WebView) {
        webViewInstance = webView
        _webViewReady.value = true
    }
    
    /**
     * 获取WebView实例
     */
    fun getWebView(): WebView? = webViewInstance
    
    /**
     * 更新当前URL
     */
    fun updateCurrentUrl(url: String) {
        _currentUrl.value = url
    }
    
    /**
     * 更新WebView进度
     */
    fun updateProgress(progress: Int) {
        _webViewProgress.value = progress.coerceIn(0, 100)
    }
    
    /**
     * 更新导航状态
     */
    fun updateNavigationState(canBack: Boolean, canForward: Boolean) {
        _canGoBack.value = canBack
        _canGoForward.value = canForward
    }
    
    /**
     * 刷新WebView
     */
    fun refreshWebView() {
        webViewInstance?.reload()
    }
    
    /**
     * WebView返回
     */
    fun goBack() {
        webViewInstance?.goBack()
    }
    
    /**
     * WebView前进
     */
    fun goForward() {
        webViewInstance?.goForward()
    }
    
    /**
     * 回到首页
     */
    fun goHome() {
        webViewInstance?.loadUrl(HttpApiConstants.PhoneUrls.home)
    }
    
    /**
     * 加载指定URL
     */
    fun loadUrl(url: String) {
        webViewInstance?.loadUrl(url)
    }
    
    /**
     * 打开抽屉
     */
    fun openDrawer() {
        _isDrawerOpen.value = true
    }
    
    /**
     * 关闭抽屉
     */
    fun closeDrawer() {
        _isDrawerOpen.value = false
    }
    
    /**
     * 切换抽屉状态
     */
    fun toggleDrawer() {
        _isDrawerOpen.value = !_isDrawerOpen.value
    }
    
    /**
     * 加载当前账号
     */
    private fun loadCurrentAccount() {
        viewModelScope.launch {
            val userDataManager = UserDataManager.getInstance(getApplication())
            val savedCurrentAccount = userDataManager.getCurrentAccount()
            if (savedCurrentAccount != null) {
                _currentAccount.value = savedCurrentAccount
            } else {
                // 如果没有保存的当前账号，使用第一个账号
                val accounts = userDataManager.getAllUserAccounts()
                if (accounts.isNotEmpty()) {
                    val firstAccount = accounts.first()
                    _currentAccount.value = firstAccount
                    userDataManager.setCurrentAccount(firstAccount.userId)
                }
            }
        }
    }
    
    /**
     * 设置当前账号
     */
    fun setCurrentAccount(account: UserAccount) {
        _currentAccount.value = account
        viewModelScope.launch {
            val userDataManager = UserDataManager.getInstance(getApplication())
            userDataManager.setCurrentAccount(account.userId)
        }
    }
    
    /**
     * 清除当前账号
     */
    fun clearCurrentAccount() {
        _currentAccount.value = null
    }
    
    /**
     * 处理登录检测
     */
    fun handleLoginDetected(userId: String, username: String, cookie: String) {
        viewModelScope.launch {
            val loginHandler = com.promise.jokerdream.ui.account.LoginHandler(
                context = getApplication(),
                onAccountUpdated = { account -> 
                    _currentAccount.value = account
                }
            )
            loginHandler.handleLoginDetected(userId, username, cookie)
        }
    }
    
    /**
     * 应用账号Cookie
     */
    fun applyAccountCookie(account: UserAccount) {
        webViewInstance?.let { webView ->
            viewModelScope.launch {
                try {
                    val cookieManager = android.webkit.CookieManager.getInstance()
                    cookieManager.setAcceptCookie(true)
                    // 清除现有Cookie
                    cookieManager.removeAllCookies(null)
                    
                    // 设置账号的Cookie
                    val cookies = account.cookie.split(";")
                    val cookieDomains = listOf(HttpApiConstants.PhoneUrls.home, HttpApiConstants.PcUrls.base)
                    cookies.forEach { cookie ->
                        if (cookie.isNotEmpty()) {
                            cookieDomains.forEach { domain ->
                                cookieManager.setCookie(domain, cookie)
                            }
                        }
                    }
                    cookieManager.flush()
                    
                    // 重新加载页面
                    webView.loadUrl(HttpApiConstants.PhoneUrls.home)
                } catch (e: Exception) {
                    Log.e("MainViewModel", "应用账号Cookie失败: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 保存WebView状态
     */
    fun saveWebViewState() {
        webViewInstance?.let { webView ->
            try {
                webView.saveState(android.os.Bundle())
            } catch (e: Exception) {
                Log.e("MainViewModel", "保存WebView状态失败: ${e.message}")
            }
        }
    }
    
    /**
     * 恢复WebView状态
     */
    fun restoreWebViewState() {
        webViewInstance?.let { webView ->
            try {
                webView.restoreState(android.os.Bundle())
            } catch (e: Exception) {
                Log.e("MainViewModel", "恢复WebView状态失败: ${e.message}")
            }
        }
    }
    
    /**
     * 清除所有Cookie
     */
    fun clearAllCookies() {
        webViewInstance?.let { webView ->
            viewModelScope.launch {
                try {
                    val cookieManager = android.webkit.CookieManager.getInstance()
                    cookieManager.removeAllCookies(null)
                    cookieManager.flush()
                    webView.reload()
                } catch (e: Exception) {
                    Log.e("MainViewModel", "清除Cookie失败: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 复制当前Cookie到剪贴板
     */
    fun copyCurrentCookie() {
        viewModelScope.launch {
            try {
                val currentAccount = _currentAccount.value
                if (currentAccount != null && currentAccount.cookie.isNotEmpty()) {
                    val clipboardManager = getApplication<Application>().getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
                    val clip = android.content.ClipData.newPlainText("Cookie", currentAccount.cookie)
                    clipboardManager.setPrimaryClip(clip)
                    Log.d("MainViewModel", "Cookie已复制到剪贴板")
                } else {
                    Log.w("MainViewModel", "当前账户没有Cookie信息")
                }
            } catch (e: Exception) {
                Log.e("MainViewModel", "复制Cookie失败: ${e.message}")
            }
        }
    }
    
    /**
     * 更新战斗过程解析进度
     */
    fun updateFightProcessProgress(currentPage: Int, totalPages: Int) {
        _fightProcessProgress.value = Pair(currentPage, totalPages)
    }
    
    /**
     * 清除战斗过程解析进度
     */
    fun clearFightProcessProgress() {
        _fightProcessProgress.value = null
    }
    
    /**
     * 启动江湖长梦任务
     */
    fun startKnightDreamTask(config: KnightDreamGameConfigEntity) {
        viewModelScope.launch {
            try {
                val currentAccount = _currentAccount.value
                if (currentAccount == null) {
                    Log.w("MainViewModel", "没有当前账户，无法启动江湖长梦任务")
                    return@launch
                }
                
                // 创建工作管理器
                val workManager = KnightDreamWorkManager.getInstance()
                // 创建江湖长梦工作
                val knightDreamWork = KnightDreamWork(currentAccount.userId, config)
                // 添加工作到管理器
                workManager.addWork(knightDreamWork)

                Log.d("MainViewModel", "江湖长梦任务已启动")
                
            } catch (e: Exception) {
                Log.e("MainViewModel", "启动江湖长梦任务失败: ${e.message}")
                e.printStackTrace()
            }
        }
    }
}
